package com.yuzhou.controller;

import com.alibaba.fastjson.JSONObject;
import com.yuzhou.domain.User;
import com.yuzhou.help.HttpRequestHelp;
import com.yuzhou.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {
    private static final String WX_APPID = "wx37be3adebe2d603e";
    private static final String WX_SECRET = "51f80d18aece2802ab38a9ea6abc9815";
    private static final String WX_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
    @Autowired
    private UserService userService;
    //登陆
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Object login(String code, String nickName, String avatarUrl)
    {
        String openId = code2OpenId(code);
//        根据openId获取登陆信息
        User user = userService.findByOpenId(openId);
        if(user == null)
        {
            //保存新用户
            user = new User();
            user.setNickName(nickName);
            user.setAvatarUrl(avatarUrl);
            user.setOpenId(openId);
            user.setTopScore(0);
            userService.add(user);
        }
        System.out.println(user);
        return "success";
    }

    @RequestMapping( value = "/updateTopScore",method = RequestMethod.POST)
    public Object updateTopScore(String code, int topScore)
    {
        String openId = code2OpenId(code);
//        根据openId获取登陆信息
        User user = userService.findByOpenId(openId);
        if(user == null)
        {
           return "error";
        }
        user.setTopScore(topScore);
        userService.updateTopScore(user);
        return "success";
    }
    private String code2OpenId(String code){
        String url = String.format(WX_URL,WX_APPID,WX_SECRET,code);
        JSONObject jsonObject = HttpRequestHelp.httpGet(url);
        return jsonObject.getString("openid");
    }


    @GetMapping("/test")
    public String test() {
        return "hhhh";
    }
}
